<template>
    <el-container class="viewer-body">
      <el-header class="header" style="padding-top: 9px">
        <el-button-group style="line-height: 50px;float: left;">
          <el-tooltip content="下载BPMN Xml文件" placement="bottom" effect="light">
            <el-button size="small" @click="handleDownloadXml" >
              <Download size="18" color="#ababab"></Download>
            </el-button>
          </el-tooltip>
          <el-tooltip content="下载流程图" placement="bottom" effect="light">
            <el-button size="small" @click="handleDownloadPic" >
              <Image size="18" color="#ababab"></Image>
            </el-button>
          </el-tooltip>
        </el-button-group>
        <el-button-group style="line-height: 50px;float: left;margin:0px 15px;">
          <el-tooltip content="缩小布局" placement="bottom" effect="light">
            <el-button  size="small" @click="handleZoomOut">
              <el-icon size="18" color="#ababab"><ZoomOut /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="自适应布局" placement="bottom" effect="light">
            <el-button  size="small" @click="handleZoom0">
              {{zoom+"%"}}
            </el-button>
          </el-tooltip>
          <el-tooltip content="放大布局" placement="bottom" effect="light">
            <el-button  size="small" @click="handleZoomIn" >
              <el-icon size="18" color="#ababab"><ZoomIn /></el-icon>
            </el-button>
          </el-tooltip>
        </el-button-group>
      </el-header>
      <el-main class="hp-main-body">
        <div id="container"></div>
      </el-main>
    </el-container>
  <div class="node-tooltip" ref="node-tooltip">
    <el-popover
        :width="700"
        :visible="tooltip.visible">
      <template #reference>
        &nbsp;&nbsp;
      </template>
      <template #default>
        <div v-if="tooltip.list.length==0" style="white-space: pre-wrap;" v-html="tooltip.tipContent"></div>
        <el-table v-else :data="tooltip.list" class="hp-tip-table">
          <el-table-column width="80" property="userName" label="操作人" />
          <el-table-column width="100" property="startTime" label="开始时间" />
          <el-table-column width="100" property="endTime" label="结束时间" />
          <el-table-column width="120" property="duration" label="耗时" />
          <el-table-column width="100" property="operateType" label="操作类型" />
          <el-table-column width="100" property="operateNote" label="操作备注" />
          <el-table-column width="100" property="cacelReson" label="取消原因" />
        </el-table>
      </template>
    </el-popover>
  </div>
</template>
<script>
import {Download, Image, Save} from 'lucide-vue-next';
import BpmnViewer from 'bpmn-js/lib/Viewer';
// 自定义render
import customBisDesignRenderModule from '@/components/render/BisDesign';
import customDevDesignRenderModule from '@/components/render/DevDesign';
// 导入汉化包
import customTranslate from '@/components/customTranslate/customTranslate'
import magicModdleDescriptor from '@/components/activiti/descriptors/activiti.json';
import {getDevViewer} from "@/api/DevForDesignApi"
import MoveCanvasModule from 'diagram-js/lib/navigation/movecanvas'

export default {
  components: { Download,Image,Save },
  props:{
    processId:{
      type: String,
      default:null
    },
    flowDataNotice:{
      type:Function,
      default:null
    },
    mode:{
      type:String,
      default:'DEV'
    },
    flow: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      zoom:100,
      codeXml:'',
      palette:true,
      designViewer:true,
      containerEl: null,
      propertiesEl:null,
      bpmnModeler: null,
      fileList: [],
      formData:{
        name:"测试表单",
        category:"分类",
        modelId:"",
        key:"",
        content:""
      },
      customRenderer:{},
      tooltip:{
        nodeId:'',//当前渲染的是谁的，如果相同则不重复渲染
        visible:false,
        tipTitle:'Title',
        tipContent:'content',
        list:[]
      }
    };
  },
  computed:{
    processInstanceId(){
      return this.processId || this.$route.params.id
    }
  },
  mounted() {
    this.containerEl = document.getElementById('container');
    // 添加翻译组件
    var customTranslateModule = {
      translate: ['value', customTranslate]
    }
    let temp = customDevDesignRenderModule;
    if(this.mode=='BIS'){
      temp = customBisDesignRenderModule
    }
    this.bpmnModeler = new BpmnViewer({
      container: this.containerEl,
      additionalModules: [
        customTranslateModule,
        temp,
        MoveCanvasModule,
      ],
      moddleExtensions: {
        activiti: magicModdleDescriptor
      }
    });
    // 设置tooltip
    this.customRenderer = this.bpmnModeler.get('customRenderer')
    this.customRenderer.setTooltip(this.updateTooltip)
    this.initData();
  },
  methods: {
    refreshCanvas(){
      if(this.isRefreshCanvas){
        return
      }
      this.isRefreshCanvas=true;
      // 重新刷新元素
      let _this=this
      setTimeout(function (){
        for (let i = 0; i < 2; i++) {
          _this.handleZoom0()
        }
      },300)
    },
    updateTooltip(element,event,nodeId,isShow){
      if(isShow && this.tooltip.nodeId==nodeId){ // 不重复渲染
        return
      }
      let nodes = this.formData.highlights[nodeId];
      let mess = "";
      let tipObject = []
      for (let i = 0; i < nodes.length; i++) {
        if(nodes[i].tipContent){
          mess += nodes[i].tipContent+"<br/>"
        }
        if(nodes[i].tipObject){
          tipObject.push(nodes[i].tipObject)
        }
      }
      this.tooltip.list = tipObject
      let el = this.$refs["node-tooltip"];
      this.tooltip.visible=isShow
      if(isShow){
        this.tooltip.nodeId = nodeId;
        this.tooltip.tipTitle = nodes.tipTitle||''
        this.tooltip.tipContent = mess
        let x = (event.originalEvent.offsetX+5)
        let y = (event.originalEvent.offsetY+30)
        el.style = "left:"+x+"px;top:"+y+"px"
      }else{
        this.tooltip.nodeId = '';
      }
    },
    async initData() {
      let flow = null
      // 已经初始过了
      let isLocalInit = false
      if(this.flow.processInstanceId){
        flow = this.flow
        isLocalInit = true
      }
      if (!flow && this.processInstanceId) {
        let res = await getDevViewer({processInstanceId: this.processInstanceId});
        if(res.success){
          flow = res.data.viewer
        }else {
          this.$notify.warning({
            title: '提示',
            message: '未找到对应的流程信息，请稍后重试~',
            showClose: false,
          })
        }
      }
      if(flow){
        this.formData = flow
        // 流程上显示高亮的数据
        if(flow.highlights){
          this.customRenderer.setHighlight(flow.highlights)
        }
        // 如果是初始化过了，则不通知
        if(!isLocalInit && this.flowDataNotice){
          this.flowDataNotice(flow)
        }
        if (flow.content) {
          this.setContent(flow.content)
        } else {
          this.$notify.warning({
            title: '提示',
            message: '未找到对应的流程实例文件，请稍后重试~',
            showClose: false,
          })
        }
      }
    },
    async setContent(xml) {
      await this.bpmnModeler.importXML(xml);
      this.handleZoom0()
    },
    handleDownloadXml() {
      this.bpmnModeler.saveXML({format: true}, (err, data) => {
        const dataTrack = 'bpmn';
        const a = document.createElement('a');
        const name = `diagram.${dataTrack}`;
        a.setAttribute(
            'href',
            `data:application/bpmn20-xml;charset=UTF-8,${encodeURIComponent(data)}`
        );
        a.setAttribute('target', '_blank');
        a.setAttribute('dataTrack', `diagram:download-${dataTrack}`);
        a.setAttribute('download', name);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      });
    },
    handleDownloadPic() {
      this.bpmnModeler.saveSVG({format: true}, (err, data) => {
        const dataTrack = 'svg';
        const a = document.createElement('a');
        const name = `diagram.${dataTrack}`;
        a.setAttribute(
            'href',
            `data:application/bpmn20-xml;charset=UTF-8,${encodeURIComponent(data)}`
        );
        a.setAttribute('target', '_blank');
        a.setAttribute('dataTrack', `diagram:download-${dataTrack}`);
        a.setAttribute('download', name);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      });
    },
    handleZoom0() {
      this.zoom = parseInt(this.bpmnModeler.get('canvas').zoom('fit-viewport') * 100);
    },
    handleZoomOut() {
      this.zoom = this.zoom - 10;
      if (this.zoom < 10) {
        this.zoom = 10;
      }
      this.bpmnModeler.get('canvas').zoom(this.zoom / 100);
    },
    handleZoomIn() {
      this.zoom = this.zoom + 10;
      this.bpmnModeler.get('canvas').zoom(this.zoom / 100);
    }
  }
}
</script>
<style scoped>
@import '@/css/base.css';
.header {
  border: none;
  background-color: #fefefe;
  height: 43px;
  border-bottom: 1px solid #dfdfdf;
}
.viewer-body {
  padding: 0px;
  margin: 0px;
  height: 100%;
}
#container {
  width: 100%;
  height: 100%;
  float: left;
}

.node-tooltip {
  position: absolute;
}
</style>
